package com.eiisan.security.filter;

import com.eiisan.security.service.CustomUserDetailsService;
import com.eiisan.security.util.JWTTokenUtil;
import com.eiisan.security.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author eii
 * @sice 2020/11/6
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        // 验证token并返回对应的用户信息
        String jwt = tokenUtil.getRealToken(request);
        Authentication authentication;
        if (StringUtils.hasText(jwt) && (authentication = tokenUtil.getAuthentication(jwt)) != null) {            //验证JWT是否正确
            //获取用户认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);     //将用户保存到SecurityContext
        }
        filterChain.doFilter(request, response);
    }
}

